package com.hmall.zookeeper.Impl;

import com.hmall.enums.RpcErrorMessageEnum;
import com.hmall.exception.RpcException;
import com.hmall.loadbalancer.Impl.ConsistentHashLoadBalance;
import com.hmall.loadbalancer.LoadBalance;
import com.hmall.remoting.dto.RpcRequest;
import com.hmall.zookeeper.ServiceDiscovery;
import com.hmall.zookeeper.utils.CuratorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.net.InetSocketAddress;
import java.util.List;

/**
 * 服务拉取
 * Zookeeper实现
 */
@Slf4j
@Component
public class ZkServiceDiscoveryImpl implements ServiceDiscovery {

    private final LoadBalance loadBalance;

    public ZkServiceDiscoveryImpl() {
        loadBalance = new ConsistentHashLoadBalance();
    }



    @Override
    public InetSocketAddress lookupService(RpcRequest request) {
        String rpcServiceName = request.getRpcServiceName();
        CuratorFramework zkClient = CuratorUtils.getZkClient();
        List<String> serviceUrlList = CuratorUtils.getChildrenNodes(zkClient, rpcServiceName);
        if (serviceUrlList.isEmpty()) {
            throw new RpcException(RpcErrorMessageEnum.SERVICE_CAN_NOT_BE_FOUND, rpcServiceName);
        }
        String targetServiceUrl = loadBalance.selectServiceAddress(serviceUrlList, request);
        log.info("Successfully found the service address:[{}]", targetServiceUrl);
        String[] socketAddressArray = targetServiceUrl.split(":");
        String host = socketAddressArray[0];
        String port = socketAddressArray[1];
        return new InetSocketAddress(host, Integer.parseInt(port));
    }
}
